package com.magold.modifier;

import org.andengine.entity.IEntity;
import org.andengine.entity.modifier.SingleValueSpanEntityModifier;
import org.andengine.util.modifier.ease.IEaseFunction;

import com.magold.algorithm.MagoldMath;

/**
 * @author Eternity
 *
 */
public class CircleMoveModifier extends SingleValueSpanEntityModifier {
	private final float mFromX, mFromY;
	private final float mToX, mToY;
	private final float mStartAngle;
	private final float mCenterX, mCenterY;
	private final float mRadius;
	private final int mCWFactor;
	
	public CircleMoveModifier(boolean pCW, float pDuration, float pFromX, float pFromY, float pToX, float pToY, IEaseFunction pEase, IEntityModifierListener pListener) {
		super(pDuration, 0, (float) Math.PI, pListener, pEase);
		mFromX = pFromX; mFromY = pFromY;
		mToX = pToX; mToY = pToY;
		mCenterX = (pToX - pFromX) / 2 + pFromX;
		mCenterY = (pToY - pFromY) / 2 + pFromY;
		mRadius = MagoldMath.distance(pFromX, pFromY, pToX, pToY) / 2;
		mStartAngle = (float) Math.atan2(mFromY - mCenterY, mFromX - mCenterX);
		
		mCWFactor = pCW ? 1 : -1;
	}

	@Override
	public CircleMoveModifier deepCopy() throws DeepCopyNotSupportedException {
		return new CircleMoveModifier(mCWFactor==1, mDuration, mFromX, mFromY, mToX, mToY, mEaseFunction, null);
	}

	@Override
	protected void onSetInitialValue(IEntity pItem, float pValue) {
		pItem.setPosition(mFromX, mFromY);
	}

	@Override
	protected void onSetValue(IEntity pItem, float pPercentageDone, float pValue) {
		pValue *= mCWFactor;
		float dx = (float) Math.cos(pValue + mStartAngle);
		float dy = (float) Math.sin(pValue + mStartAngle);
		pItem.setPosition(mCenterX + dx*mRadius, mCenterY + dy*mRadius);
	}
	
}
